/*
 * Project Name: jmax
 * File Name: Task.java
 * Copyright: Copyright(C) 1985-2015 ZKTeco Inc. All rights reserved.
 */
package com.xdtech.sys.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.xdtech.common.utils.ApplicationContextUtil;
import com.xdtech.sys.vo.TaskItem;

/**
 * TODO 一句话功能简述，请确保和下面的block tags之间保留一行空行
 * <p>
 * TODO 功能详细描述，若不需要请连同上面的p标签一起删除
 * 
 * @author <a href="max.zheng@zkteco.com">郑志雄</>
 * @version TODO 添加版本
 * @see 相关类或方法，不需要请删除此行
 * @since 2015-5-12 下午5:53:15
 */
public class TaskUtils
{
	public static Logger log = Logger.getLogger(TaskUtils.class);  
	  
    /** 
     * 通过反射调用scheduleJob中定义的方法 
     *  
     * @param scheduleJob 
     */  
    public static void invokMethod(TaskItem taskItem) {  
        Object object = null;  
        Class clazz = null;  
                //springId不为空先按springId查找bean  
        if (StringUtils.isNotBlank(taskItem.getTarget())) {
        	try {
        		 object = ApplicationContextUtil.getContext().getBean(taskItem.getTarget());
			} catch (Exception e) {
				//获取不到
				object = null;
			}
           
            if (object==null) {
                 try {  
                     clazz = Class.forName(taskItem.getTarget());  
                     object = clazz.newInstance();  
                 } catch (Exception e) {  
                     log.error("init task object error",e);
                 }
			}
        } 
       
        if (object == null) {  
            log.error("任务名称 = [" + taskItem.getName() + "]---------------未启动成功，请检查是否配置正确！！！");  
            return;  
        }  
        clazz = object.getClass();  
        Method method = null;  
        try {  
            method = clazz.getDeclaredMethod(taskItem.getMethod());  
        } catch (NoSuchMethodException e) {  
            log.error("任务名称 = [" + taskItem.getName() + "]---------------未启动成功，方法名设置错误！！！");  
        } catch (SecurityException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        if (method != null) {  
            try {  
                method.invoke(object);  
            } catch (IllegalAccessException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            } catch (IllegalArgumentException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            } catch (InvocationTargetException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
        }  
          
    }  
}
